<!-- My Bots -->
<!-- Author: Edwin -->
<template>
  <div class="bot_entrey_index">
    <botHeaders :viewValue="viewValue"
                @clickDropdown="clickDropdown"
                @botViewReportLink="botViewlinkreport"
                :pageheaderName="pageheaderName"></botHeaders>
    <el-card v-if="viewValue === 'Grid'"
             style="height:100%;margin-top:9px"
             shadow="never"
             class="aui-card--fill msp_bots">
      <div>
        <el-form :inline="true">
          <el-form-item>
            <el-button size="small"
                       type="primary"
                       v-if="$hasPermission('sys:bots:add')"
                       @click="addOrUpdateNewBots()">{{ $t('new') }}
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-switch v-model="dataForm.showAllIntegration"
                       :active-text="$t('custom.dataset.showAllIntegration')"
                       @change="getDataList"></el-switch>
          </el-form-item>
          <el-form-item v-if="$route.path === '/Bots'">
            <el-switch v-model="clientSetting.value"
                       :active-text="$t('custom.bots.all_message_switch')"
                       active-color="#ff4949"
                       v-if="$hasPermission('sys:bots:allmessageswitch')"
                       @change="messageSwitchDialog()">
            </el-switch>
          </el-form-item>
          <el-form-item>
            <el-button size="small"
                       type="primary"
                       :loading="botmessagereportLinkLoading"
                       @click="botmessagereportLink()">{{ $t('custom.bots.botmessagereport') }}
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-button size="small"
                       type="primary"
                       :loading="bottriggerreportLinkLoading"
                       @click="bottriggerreportLink()">{{ $t('custom.bots.bottriggerreport') }}
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-button size="small"
                       type="primary"
                       :loading="botuseagereportLinkLoading"
                       @click="botuseagereportLink()">{{ $t('custom.bots.botusagereport') }}
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-button size="small"
                       type="primary"
                       v-if="$hasPermission('sys:bots:psastatussetting')"
                       @click="openPSASetupDialog()">{{ $t('custom.bots.psaStatusSetting') }}
            </el-button>
          </el-form-item>
          <!-- <el-form-item style="float: right;">
            <el-button type="text"
                      @click="$router.push({ name: 'mspbots-client-desired-index' })"><i class="el-icon-star-off"></i>{{ $t('custom.bots.rightlink') }}
            </el-button>
          </el-form-item> -->
        </el-form>
        <div class="control-section">
          <div class="content-wrapper"
               v-loading="dataListLoading">
            <ejs-grid :dataSource="dataList"
                      :allowResizing='gridDefaultSetting.allowResizing'
                      :allowFiltering='gridDefaultSetting.allowFiltering'
                      :filterSettings='gridDefaultSetting.filterSettings'
                      :allowGrouping='true'
                      :allowPaging='true'
                      :toolbar="gridDefaultSetting.toolbar"
                      :allowTextWrap="gridDefaultSetting.allowTextWrap"
                      :showColumnChooser='gridDefaultSetting.showColumnChooser'
                      :allowReordering='gridDefaultSetting.allowReordering'
                      :allowSorting='true'
                      :sortSettings='sortSettings'
                      :editSettings='editSettings'
                      ref="bot-grid"
                      height="56vh"
                      :selectionSettings='gridDefaultSetting.selectOptions'
                      :rowSelected='dataListSelectionChangeHandle'
                      :pageSettings='pageSettings'
                      :showColumnMenu='gridDefaultSetting.showColumnMenu'>
              <e-columns>
                <e-column field='name'
                          :headerText="$t('custom.bots.name')"
                          :template='BotNameFormat'
                          :width='200'></e-column>
                <!--  clipMode='EllipsisWithTooltip' -->
                <!-- <e-column :headerText="$t('custom.bots.customize')"
                          :template="BotBtn"
                          width='230'
                          textAlign='Right'></e-column> -->
                <e-column field='integration'
                          :headerText="$t('custom.reports.integration')"
                          :autoFit='true'
                          :width='130'></e-column>
                <e-column field='classification'
                          :headerText="$t('custom.reports.classification')"
                          :autoFit='true'
                          :width='130'></e-column>
                <e-column field='description'
                          :headerText="$t('custom.bots.description')"
                          clipMode='EllipsisWithTooltip'
                          :width='200'></e-column>
                <e-column field='enable'
                          :headerText="$t('custom.bots.trigger')"
                          :width='90'
                          :template='BotEnableFormat'
                          :headerTemplate='enableTooltip'
                          v-if="$hasPermission('sys:bots:edit')"></e-column>
                <e-column field='alert'
                          :headerText="$t('custom.bots.alert')"
                          :width='90'
                          :template='BotSendFormat'
                          :headerTemplate='alertTooltip'
                          v-if="$hasPermission('sys:bots:edit')"></e-column>
                <e-column field='escalation'
                          :headerText="$t('custom.bots.escalate')"
                          :width='100'
                          :autoFit='true'
                          :template='BotEscalationFormat'
                          :headerTemplate='escalationTooltip'
                          v-if="$hasPermission('sys:bots:edit')"></e-column>
                <e-column field='ready'
                          :headerText="$t('custom.bots.ready')"
                          :template='MessageStatusLinkReady'
                          :headerTemplate='readyTooltip'
                          :width='100'></e-column>
                <e-column field='received'
                          :headerText="$t('custom.bots.received')"
                          :template='MessageStatusLinkReceived'
                          :headerTemplate='receivedTooltip'
                          :width='100'></e-column>
                <e-column field='read'
                          :headerText="$t('custom.bots.read')"
                          :template='MessageStatusLinkRead'
                          :headerTemplate='readTooltip'
                          :width='100'></e-column>
                <e-column field='createTime'
                          :headerText="$t('custom.bots.createTime')"
                          :width='150'
                          :template='CreateTimeFormat'></e-column>
                <e-column field='creatorName'
                          :headerText="$t('custom.bots.createdby')"
                          :width='150'></e-column>
                <e-column field='updateTime'
                          :headerText="$t('custom.bots.updateTime')"
                          :width='150'
                          :template='UpdateTimeFormat'></e-column>
                <e-column field='updateByName'
                          :headerText="$t('custom.bots.updatedby')"
                          :width='150'></e-column>
                <e-column v-if="$hasPermission('sys:reports:internalNotes')"
                          field="jiraNumber"
                          clipMode='EllipsisWithTooltip'
                          :template="JiraNumberFormat"
                          :headerText="$t('custom.reports.jiraNumber')"
                          :width="120"></e-column>
                <e-column field="poName"
                          v-if="$hasPermission('sys:reports:internalNotes')"
                          :headerText="$t('custom.reports.poName')"
                          clipMode='EllipsisWithTooltip'
                          :width="80"></e-column>
                <e-column field="daName"
                          v-if="$hasPermission('sys:reports:internalNotes')"
                          clipMode='EllipsisWithTooltip'
                          :headerText="$t('custom.reports.daName')"
                          :width="80"></e-column>
              </e-columns>
            </ejs-grid>
          </div>
        </div>
      </div>
      <el-dialog :title="$t('custom.bots.all_message_switch')"
                 :visible.sync="messageDialog"
                 @close="canceldialog"
                 width="30%">
        <div class="row">
          <div style="color:red;font-size: large;margin-bottom: 10px;">Caution:</div>
          <div style="word-break: break-word;white-space: normal;line-height: 20px;margin: 10px 10px;">
            Turning off this switch will disable all the bots' messages from being sent out to users.
            This is used for troubleshooting if you receive a large number of wrong messages.
            If you only want to turn off certain bots messages, please turn off the enable switch for each bot message.
            If you only need to turn off messages for certain users,
            please go to Settings > User Management > Action to turn off the message switch for specific users.
          </div>
        </div>
        <span slot="footer"
              class="dialog-footer">
          <el-button type="primary"
                     size="small"
                     @click="canceldialog()">{{ $t('cancel') }}</el-button>
          <el-button type="danger"
                     size="small"
                     @click="updateMessageSwitch()">{{ $t('custom.bots.confirm') }}</el-button>
        </span>
      </el-dialog>
      <BotPSASeeting ref="psa-setting-component" />
      <add-or-update v-if="addOrUpdateVisible"
                     ref="addOrUpdate"
                     @refreshDataList="getDataList"></add-or-update>
      <SelectBotTemplate ref="addUpdateObj"
                         @showDataForm="jumpDataForm"></SelectBotTemplate>
      <AddUpdateBak ref="addUpdateBak"
                    @reselectTemplate="reselectTemplateFn"
                    :parentStateObj="botTem"
                    :botType="botType"
                    @refreshList="getDataList"></AddUpdateBak>
    </el-card>
    <div v-if="viewValue === 'List'"
         shadow="never"
         style="height:100%">
      <botListView ref="ListBot"></botListView>
    </div>

  </div>

</template>
<script>
import Vue from 'vue'

import mixinViewModule from '@/mixins/crud-view-module'
import AddOrUpdate from './bot-edit'

import BotEnableFormat from './BotFormatComponents/BotEnableFormat'
import BotSendFormat from './BotFormatComponents/BotSendFormat'
import BotEscalationFormat from './BotFormatComponents/BotEscalationFormat'
import BotPSASeeting from './bot-psa-setting'
import { LinkComponent } from './BotFormatComponents/LinkComponent.js'
import CreateTimeFormat from './BotFormatComponents/CreateDateFormat'
import UpdateTimeFormat from './BotFormatComponents/UpdateTimeFormat'
import MessageStatusLinkRead from './BotFormatComponents/MessageStatusLinkRead'
import MessageStatusLinkReady from './BotFormatComponents/MessageStatusLinkReady'
import MessageStatusLinkReceived from './BotFormatComponents/MessageStatusLinkReceived'
import BotNameFormat from './BotFormatComponents/BotNameFormat'
import SelectBotTemplate from './select-bot-tempalte'
import AddUpdateBak from './add-or-update-bak'
import botListView from './bot-list-view.vue'
import botHeaders from './viewComponents/bot-headers.vue'
import JiraNumberFormat from './components/JiraNumberFormat'
import { fetchSetting, setSetting, deleteBotInfoApi } from '@/api/new'


export default {
  mixins: [mixinViewModule],
  data () {
    return {
      pageheaderName: this.$route.path.includes('CrossTenant') ? 'Internal Bots' : 'Bots',
      viewValue: localStorage.getItem('botview') ? localStorage.getItem('botview') : 'List',
      botType: '',
      botTem: -1,
      mybotsadd: false,
      mixinViewModuleOptions: {
        getDataListURL: '/web/bots/sys/bot/list-integration',
        getDataListIsPage: false
      },
      dataForm: {
        disable: true,
        scope: this.pageSource,
        showAllIntegration: !!window.location.pathname.includes('CrossTenant'),
        internal: this.IsInternal(),
        businessType: window.location.pathname === '/Bots' ? 'Custom' : window.location.pathname === '/CrossTenantBots' ? 'MSPbots Internal' : 'Template'
      },
      scope: [],
      clientSetting: {
        keyword: 'teams.message.switch',
        value: false,
        type: 'BOT_SETTING'
      },
      loading: false,
      commands: [{
        type: 'Edit',
        buttonOption: { content: this.$t('custom.bots.editbtn'), cssClass: 'e-outline e-small e-primary' }
      }],
      BotEnableFormat: function () {
        return { template: BotEnableFormat }
      },
      BotSendFormat: function () {
        return { template: BotSendFormat }
      },
      BotEscalationFormat: function () {
        return { template: BotEscalationFormat }
      },
      CreateTimeFormat: function () {
        return { template: CreateTimeFormat }
      },
      UpdateTimeFormat: function () {
        return { template: UpdateTimeFormat }
      },
      MessageStatusLinkRead: function () {
        return { template: MessageStatusLinkRead }
      },
      MessageStatusLinkReady: function () {
        return { template: MessageStatusLinkReady }
      },
      MessageStatusLinkReceived: function () {
        return { template: MessageStatusLinkReceived }
      },
      BotNameFormat: function () {
        return { template: BotNameFormat }
      },
      BotBtn: function () {
        return { template: BotBtn }
      },
      JiraNumberFormat: function () {
        return { template: JiraNumberFormat }
      },
      editSettings: {
        allowDeleting: false,
        allowAdding: false,
        mode: 'Cell'
      },
      messageDialog: false,
      sortSettings: {
        columns: [
          { field: 'name', direction: 'Ascending' },
          { field: 'updateTime', direction: 'Ascending' }
        ]
      }, // Descending
      pageSettings: { pageSize: 100, pageSizes: [50, 100, 200, 1000], pageCount: 4 },
      enableTooltip: function () {
        return {
          template: Vue.component('enableTooltip', {
            template: `<el-tooltip open-delay="1000" class="item" effect="dark" content='That which sets off an action.  Switching this on enables the bot to generate messages. You can view these messages in the message dashboard. Generated messages will be in “ready” status.' placement="top">
                        <div style="text-align:left">Trigger</div>
                        </el-tooltip>`
          })
        }
      },
      alertTooltip: function () {
        return {
          template: Vue.component('alertTooltip', {
            template: `<el-tooltip open-delay="1000" class="item" effect="dark" content="Generated messages intended for end-users.  Switching this on enables the bot to send these messages to intended recipients/users." placement="top">
                        <div style="text-align:left">Alert</div>
                        </el-tooltip>`
          })
        }
      },
      escalationTooltip: function () {
        return {
          template: Vue.component('escalationTooltip', {
            template: `<el-tooltip open-delay="1000" class="item" effect="dark" content="The bot will pass on or escalate the message to the user's managers depending on the escalation settings.  Escalation is triggered when the same issue has happened to the user repeatedly. " placement="top">
                        <div style="text-align:left">Escalate</div>
                        </el-tooltip>`
          })
        }
      },
      readyTooltip: function () {
        return {
          template: Vue.component('readyTooltip', {
            template: `<el-tooltip open-delay="1000" class="item" effect="dark" content='This counts the number of messages that the bot has generated but have stayed in the “ready” status in the last 7 days.  Meaning, the messages have not been sent to the intended recipients/users.' placement="top">
                        <div style="text-align:left">Ready</div>
                        </el-tooltip>`
          })
        }
      },
      receivedTooltip: function () {
        return {
          template: Vue.component('receivedTooltip', {
            template: `<el-tooltip open-delay="1000" class="item" effect="dark" content="This counts the number of messages that the users have received but have not read yet." placement="top">
                        <div style="text-align:left">Received</div>
                        </el-tooltip>`
          })
        }
      },
      readTooltip: function () {
        return {
          template: Vue.component('readTooltip', {
            template: `<el-tooltip open-delay="1000" class="item" effect="dark" content="This counts the number of messages the users have read.  Meaning, the intended recipients/users received and read the messages/alerts." placement="top">
                        <div style="text-align:left">Read</div>
                        </el-tooltip>`
          })
        }
      },
      botmessagereportLinkLoading: false,
      bottriggerreportLinkLoading: false,
      botuseagereportLinkLoading: false
    }
  },
  components: {
    AddOrUpdate,
    BotPSASeeting,
    SelectBotTemplate,
    AddUpdateBak,
    botListView,
    botHeaders
  },
  props: {
    pageSource: {
      type: String,
      default: null
    }
  },

  created () {
    this.init()
    this.lisonPathEmit()
  },
  destroyed () {
    LinkComponent.$off('initPageList')
    LinkComponent.$off('changeSwitchHanderForGrid')
    LinkComponent.$off('showEdit')
    // LinkComponent.$off('showInEdit')
    // LinkComponent.$off('showTyEdit')
  },
  methods: {
    clickDropdown (val) {
      if (val === 'Grid') {
        this.getMessageSwitch()
        this.query()
      }
      localStorage.setItem('botview', val)
      this.viewValue = val
    },
    lisonPathEmit () {
      LinkComponent.$on('showEdit', (data) => {
        this.showEdit(data)
      })
    },
    reselectTemplateFn () {
      this.$nextTick(() => {
        this.$refs.addUpdateBak.visible = false
        this.$refs.addUpdateObj.visible = true
      })
    },
    jumpDataForm (item) {
      this.$nextTick(() => {
        this.$refs.addUpdateBak.init()
      })
      this.botTem = item.item
      this.botType = item.type
    },
    IsInternal () {
      let path = window.location.pathname
      if (path === '/CrossTenantBots') {
        return true
      } else {
        return false
      }
    },
    init () {
      if (localStorage.getItem('botview') === 'Grid') this.getMessageSwitch()
      LinkComponent.$on('initPageList', () => {
        // if (localStorage.getItem('botview') === 'Grid') this.getDataList()
        this.getDataList()
      })
      LinkComponent.$on('changeSwitchHanderForGrid', (data, params) => {
        this.resetDataList(data, params)
      })
    },
    resetDataList (data, params) {
      let findItem = this.dataList.find(e => {
        return e.id === data.id
      })
      if (findItem) {
        if (findItem.version === '1') {
          findItem.alert = params.paramsValue.send
          findItem.enable = params.enable
          findItem.escalation = params.paramsValue.sendEscalation
        } else {
          findItem.alert = params.alert
          findItem.enable = params.enable
          findItem.escalation = params.escalation
        }
      }
      this.$forceUpdate()
      if (this.$refs['bot-grid']) this.$refs['bot-grid'].ej2Instances.refresh()
    },
    commandClick (type, row) {
      if (type === 'Edit') {
        this.addOrUpdateNewBots(row.id)
      }
      if (type === 'EditOld') {
        this.addOrUpdateHandle(row.id)
      }
      if (type === 'Delete') {
        this.deleteBots(row.id)
      }
      if (type === 'Design') {
        // this.$router.push({ name: 'mspbots-bots-bak-bot-view-index', query: { botId: row.id } })
        this.$router.push({ name: 'mspbots-bots-bak-bot-design-index', query: { botId: row.id } })
      }
    },
    addBots () {
      this.mybotsadd = true
      this.$nextTick(() => {
        this.$refs.mybots.init()
      })
    },
    appintOrApp () {
      let result = new Promise(function (resolve, reject) {
        if (window.location.hostname === 'app.maibozhineng.com') {
          resolve()
        } else {
          this.reject()
        }
      })
      return result
    },
    botViewlinkreport (val) {
      if (val === '1') this.botmessagereportLink()
      if (val === '2') this.bottriggerreportLink()
      if (val === '3') this.botuseagereportLink()
    },
    async botmessagereportLink () {
      try {
        this.botmessagereportLinkLoading = true

        await this.appintOrApp()
        this.$router.push({ path: 'dashboard-1391612282257911809', query: { pageid: '1391612282257911809', layout: 'report_layout', name: 'MSPbots Generated Bot Messages' } })
      } catch (error) {
        this.$router.push({ path: 'dashboard-1391612282257911809', query: { pageid: '1391612282257911809', layout: 'report_layout', name: 'MSPbots Generated Bot Messages' } })
      } finally {
        this.botmessagereportLinkLoading = false
      }
    },
    async botuseagereportLink () {
      try {
        this.botuseagereportLinkLoading = true

        await this.appintOrApp()
        this.$router.push({ path: 'dashboard-1663822667547156481', query: { pageid: '1663822667547156481', layout: 'report_layout', name: 'Usage Report' } })
      } catch (error) {
        this.$router.push({ path: 'dashboard-1663822667547156481', query: { pageid: '1663822667547156481', layout: 'report_layout', name: 'Usage Report' } })
      } finally {
        this.botuseagereportLinkLoading = false
      }
    },
    async bottriggerreportLink () {
      try {
        this.bottriggerreportLinkLoading = true

        await this.appintOrApp()
        this.$router.push({ path: 'dashboard-1663103409926189058', query: { pageid: '1663103409926189058', layout: 'report_layout', name: 'Trigger Dashboard' } })
      } catch (error) {
        this.$router.push({ path: 'dashboard-1663103409926189058', query: { pageid: '1663103409926189058', layout: 'report_layout', name: 'Trigger Dashboard' } })
      } finally {
        this.bottriggerreportLinkLoading = false
      }
    },
    canceldialog () {
      this.messageDialog = false
      this.getMessageSwitch()
    },
    getMessageSwitch () {
      Vue['_this_my_bot_'] = this
      const params = {
        keyword: 'teams.message.switch'
      }
      fetchSetting(params).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        if (res.data) {
          let tempData = res.data
          if (tempData.value === 'false') {
            tempData.value = true
          } else {
            tempData.value = false
          }
          this.clientSetting = tempData
        }
      })
    },
    messageSwitchDialog () {
      if (this.clientSetting.value) {
        this.messageDialog = true
      } else {
        this.updateMessageSwitch()
      }
    },
    updateMessageSwitch () {
      if (!this.$store.state.user.email) {
        return this.$message.error(this.$t('custom.bots.updateBotsMessage'))
      }
      const params = {
        ...this.clientSetting,
        value: this.clientSetting.value ? 'false' : 'true',
        email: this.$store.state.user.email
      }
      setSetting(params).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.messageDialog = false
        this.getMessageSwitch()
        return this.$message.success(res.msg)
      }).catch(() => {

      })
    },
    openPSASetupDialog () {
      this.$refs['psa-setting-component'].openDialog()
    },
    formatDataList () {
      // this.dataList
      let tempList = []
      this.dataList.map(e => {
        if (e.version === '1') {
          tempList.push(e)
        }
      })
      return tempList
    },
    addOrUpdateNewBots (id) {
      this.$nextTick(() => {
        this.$refs.addUpdateObj.dataForm.id = id
        this.$refs.addUpdateObj.init()
      })
    },
    deleteBots (id) {
      this.$confirm(this.$t('prompt.info', { 'handle': this.$t('delete') }), this.$t('prompt.title'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      }).then(() => {
        const params = {
          id: id
        }
        deleteBotInfoApi(params).then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.getDataList()
          return this.$message.success(res.msg)
        })
      }).catch(() => {
      })
    },
    showEdit (data) {
      this.addOrUpdateHandle(data.id)
    }
  },
  beforeDestroy () {
    delete Vue['_this_my_bot_']
  },
  activated () {
    if (this.$store.state.bot.refreshBotList === 'refresh') this.getDataList()
  }
}

const BotBtn = Vue.component(
  'bot-btn', {
  template: `<div style="display: flex;justify-content: flex-end">
      <el-button size="mini" plain type="primary" @click="clickSelect('EditOld',$data.data)" v-if="$data.data.version == 1 && $hasPermission('sys:bots:edit')" >Edit</el-button>
      <el-button size="mini" plain type="primary" @click="clickSelect('Edit',$data.data)" v-if="$data.data.version == 2 && $hasPermission('sys:bots:edit')">Edit</el-button>
      <el-button size="mini" plain @click="clickSelect('Delete',$data.data)" v-if="$data.data.version == 2 && $hasPermission('sys:bots:delete')" type="danger">Delete</el-button>
      <el-button size="mini" plain @click="clickSelect('Design',$data.data)" v-if="$data.data.version == 2 && $hasPermission('sys:bots:design')" type="success">Design</el-button>
    </div>`,
  data () {
    return {}
  },
  methods: {
    clickSelect (e, row) {
      Vue._this_my_bot_.commandClick(e, row)
    }
  }
}
)
</script>
<style lang="scss">
.bot_entrey_index {
  height: calc(calc(100vh - 50px - 38px - 30px)) !important;
  .e-popup.e-popup-open.e-dialog {
    // display: inline-flex !important;
  }
  .e-grid .e-dialog .e-dlg-content {
    height: 200px !important;
  }
  .e-pivotfieldlist-wrapper.e-dialog {
    width: 50% !important;
    height: 90% !important;
  }
}
</style>
<style lang="scss" scoped>
</style>
